<template>
  <div class="container">
    <a-modal
      v-model:visible="visible"
      width="98%"
      draggable
      :footer="false"
      @close="resetFields"
    >
      <template #title> {{ modalTitle }} </template>
      <a-form ref="formRef" layout="vertical" :model="formData">
        <a-row :gutter="28">
          <a-col :span="2">
            <a-form-item field="platform" label="平台">
              <a-select
                  v-model="formData.platform"
                  placeholder="请选择"
                  allow-clear
              >
                <a-option
                    :value="item.value"
                    v-for="item in platformList"
                    :key="item.value"
                >{{ item.label }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item field="scenes" label="场景">
              <a-select
                  v-model="formData.scenes"
                  placeholder="请选择"
                  allow-clear
              >
                <a-option
                    :value="item.value"
                    v-for="item in scenesList"
                    :key="item.value"
                >{{ item.label }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col  :span="6">
            <a-form-item label="载体" field="carrierId">
              <a-select
                  v-model="formData.type"
                  :options="typeOptions"
                  placeholder="请选择类型"
                  @change="handleShopSearch('')"
                  allow-clear
              />
              <a-select v-model="formData.carrierId" :loading="loading" placeholder="输入店铺名" allow-search :allow-clear=true
                        :filter-option="false" @search="handleShopSearch">
                <a-option v-for="item of shopList" :key="item?.id" :value="item?.id">{{ item.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="投放时间" field="inTime">
              <a-range-picker
                showTime
                :time-picker-props="{
                defaultValue:['00:00:00','00:00:00']
                }"
                @change="onTimeChange"
                style=" width: 380px; "
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-button
              type="primary"
              :loading="loading"
              @click="searchUseLog"
              style="margin-top: 30px"
            >
              搜索
            </a-button>
            <a-button
                type="primary"
                :loading="loading"
                @click="handleLinkEditAdd({adId: formData.adId})"
                style="margin-top: 30px; margin-left: 20px;"
                status="success"
            >
              添加
            </a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        row-key="id"
        :columns="columns"
        :data="state.list"
        :pagination="pagination"
        :loading="loading"
        @page-change="pageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-popconfirm content="您确定删除吗？" @ok="onDelete(record.id)">
              <a-button type="primary" status="danger" size="mini"
              >删除</a-button
              >
            </a-popconfirm>
            <a-button type="primary" size="mini" @click="handleEdit(record)">编辑</a-button>
          </a-space>
        </template>
      </a-table>
    </a-modal>

    <linkEditAdd ref="linkEditAddRef" @fetch-data="fetchData" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import {getLinkListByQuery, deleteLink, deleteAd} from '@/api/user';
  import {cfCarParkSearch, cfChargingStationSearch} from "@/api/internetOfThings";
  import {cfVillageSearch} from "@/api/wisdomCommunity";
  import { parseTime } from '@/utils/index';
  import { cfUserQuicklySearchUser } from '@/api/user';
  import dayjs from 'dayjs';
  import linkEditAdd from './linkEditAdd.vue';

  const linkEditAddRef = ref();
  const visible = ref(false);
  const loading = ref(false);
  const selectLoading = ref(false);
  const modalTitle = ref('广告关联');
  const parkList = ref([]);
  const formRef = ref();
  const shopList = ref([]);
  const platformList = [
    { label: '微信公众号', value: 0 },
    { label: '微信小程序', value: 1 },
    { label: '微信app', value: 2 },
    { label: '阿里公众号', value: 3 },
    { label: '阿里小程序', value: 4 },
    { label: '阿里app', value: 5 },
    { label: '硬件广告屏', value: 6 },
  ];
  const scenesList = [
    { label: '车牌绑定页面', value: 0 },
    { label: '停车账单结算页面', value: 1 },
    { label: '支付成功页面', value: 2 },
    { label: '停车场详情', value: 3 },
    { label: '充电站详情', value: 4 },
    { label: '停车套餐续费页面', value: 5 },
    { label: '选充电桩下单页面', value: 6 },
    { label: '充电中页面', value: 7 },
    { label: '充电账单详情页面', value: 8 },
    { label: '硬件显示屏', value: 9 },
    { label: '移动应用首页', value: 10 },
    { label: '领取优惠券页面', value: 11 },
    { label: '订单详情页面', value: 12 },
  ];
  const typeOptions = [
    {
      label: '停车',
      value: 1,
    },
    {
      label: '商城',
      value: 2,
    },
    {
      label: '充电',
      value: 3,
    },
    {
      label: '洗车',
      value: 4,
    },
    {
      label: '加油',
      value: 5,
    },
    {
      label: '社区',
      value: 6,
    }
  ];
  /**
   * 搜索店铺（判断类型）
   * @param value
   */
  const handleShopSearch = async (value: any) => {
    if(formData.value.type==1){
      //停车
      const { data, code } = await cfCarParkSearch({
        params: {
          name: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    } else if(formData.value.type==3){
      //充电
      const { data, code } = await cfChargingStationSearch({
        params: {
          stationName: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    } else if(formData.value.type==6){
      //智慧社区
      const { data, code } = await cfVillageSearch({
        params: {
          name: value,
          page: 1,
          size: 200,
        },
      });
      if (code === 10002) {
        shopList.value = data;
      } else {
        shopList.value = [];
      }
    }else{
      //其它暂不支持
      shopList.value = [];
    }

  };
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const formData = ref({
    adId: '',
    scenes: '',
    platform: '',
    carrierId: '',
    appid: '',
    minStartTime: '',
    maxStartTime: '',
    minEndTime: '',
    maxEndTime: '',
    type: '',
  });
  const handleLinkEditAdd = (e: any) => {
    linkEditAddRef.value.handleClick(e);
  };
  const onTimeChange = (dateString: any, date: Date[]) => {
    if(date!=undefined){
      formData.value.minStartTime = dayjs(date[0]).valueOf() + '';
      formData.value.maxEndTime = dayjs(date[1]).valueOf() + '';
    }else{
      formData.value.minStartTime = '';
      formData.value.maxEndTime = '';
    }
  };
  const state = reactive({
    list: [],
  });
  const onDelete = async (id: string) => {
    await deleteLink({ params: { id } });
    fetchData();
  };
  const handleEdit = (e: any) => {
    linkEditAddRef.value.handleClick(e);
  };

  const columns = [
    {
      width: 180,
      title: 'appid',
      dataIndex: 'appid',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 120,
      title: '应用名称',
      dataIndex: 'applicationName',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 200,
      title: '场景',
      dataIndex: 'scenesName',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 115,
      title: '平台',
      dataIndex: 'platformName',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 180,
      title: '开始时间',
      dataIndex: 'newStartTime',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 180,
      title: '结束时间',
      dataIndex: 'newEndTime',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 100,
      title: '展示次数',
      dataIndex: 'showCounts',
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      width: 100,
      title: '点击次数',
      dataIndex: 'clickCounts',
      ellipsis: true,
      tooltip: {
        'background-color': '#3491FA',
      },
    },
    {
      title: '操作',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ];
  const pageChange = (e: number) => {
    pagination.current = e;
    fetchData();
  };
  const checkParams = (obj: any) => {
    // eslint-disable-next-line no-restricted-syntax, guard-for-in
    for (const i in obj) {
      if (!obj[i]) {
        if (obj[i] !== 0) {
          obj[i] = null;
        }
      }
    }
    return obj;
  };
  const handleSelectSearch = async (value: any) => {
      selectLoading.value = true;
      const { data, code } = await cfCarParkSearch({
        params: {
          name: value,
          page: 1,
          size: 200,
        },
      });
      selectLoading.value = false;
      if (code === 10002) {
        parkList.value = data;
      } else {
        parkList.value = [];
      }
  };
  const handleUserSearch = async (value: any) => {
    const { data, code } = await cfUserQuicklySearchUser({
      params: {
        phone: value,
        page: 1,
        size: 20,
      },
    });
    if (code === 10002) {
      userList.value = data;
    } else {
      userList.value = [];
    }
  };
  const searchUseLog = async () => {
    pagination.current = 1;
    fetchData();
  }
  const fetchData = async () => {
    loading.value = true;
    const { code, total, data } = await getLinkListByQuery({
      params: checkParams({
        page: pagination.current,
        size: pagination.pageSize,
        ...formData.value,
      }),
    });
    loading.value = false;
    if (code === 10002) {
      if (total) pagination.total = total;
      for (const i of data) {
        i.newStartTime = parseTime(i.startTime);
        i.newEndTime = parseTime(i.endTime);
        i.newIssuanceTime = parseTime(i.issuanceTime);
        for(let scene of scenesList){
          if(scene.value===i.scenes){
            i.scenesName = scene.label;
            break;
          }
        }
        for(let platform of platformList){
          if(platform.value===i.platform){
            i.platformName = platform.label;
            break;
          }
        }
      }
      state.list = data;
    } else {
      state.list = [];
    }
  };
  const handleClick = (queryParams: any) => {
    if(queryParams && queryParams.id){
      formData.value.adId = queryParams.id;
    }
    if(queryParams && queryParams.title){

      modalTitle.value = queryParams.title + '-' + '广告关联';
    }
    fetchData();
    handleSelectSearch(null);
    visible.value = true;
  };

  const resetFields = () => {
    formRef.value.resetFields();
  };

  defineExpose({ handleClick });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 40px 20px;
    overflow: hidden;
  }

  .actions {
    height: 60px;
    padding: 14px 20px 14px 0;
    background: var(--color-bg-2);
    text-align: right;
  }
</style>
